<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2>登录</h2>
      <el-form :model="loginData" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="loginData.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="loginData.password" show-password />
        </el-form-item>
        <el-form-item label="用户类型">
          <el-select v-model="loginData.userType" placeholder="请选择">
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-button @click="handleLogin" type="primary">登录</el-button>
      </el-form>
      <p class="register-link">
        没有账号？<router-link to="/register">立即注册</router-link>
      </p>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginData: {
        username: '',
        password: '',
        userType: 'user'
      }
    };
  },
  methods: {
    async handleLogin() {
      try {
        const response = await fetch('http://localhost:8081/api/users/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            username: this.loginData.username,
            password: this.loginData.password,
            userType: this.loginData.userType
          })
        });

        const result = await response.json();

        if (!response.ok) {
          throw new Error(result.message || '登录失败');
        }

        if (this.loginData.userType === 'admin') {
          this.$router.push('/admin');
        } else {
          this.$router.push('/user-dashboard');
        }
      } catch (error) {
        alert(error.message);
      }
    }
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.login-card {
  width: 400px;
  text-align: center;
}

.register-link {
  margin-top: 15px;
  text-align: center;
}
</style>